package com.edu.learning.concurrent.sample.mode3;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * @author ll
 * @Date 2017/10/25 15:40
 */
public class CompletionServiceDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().
                setDaemon(true).setNameFormat("CompletionServiceDemo-%d").build();
        ExecutorService executorService = new ThreadPoolExecutor(
                32,
                32,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(1024),
                threadFactory,
                new ThreadPoolExecutor.CallerRunsPolicy());

        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executorService);
        for (int i = 0; i < 5; i ++) {
            completionService.submit(new TaskInteger(i));
        }
        executorService.shutdown();

        //will block
        for (int i = 0; i < 5; i ++) {
            Future<Integer> future = completionService.take();
            System.out.println(i + "\t future.get() = " + future.get());
        }
    }

    private static class TaskInteger implements Callable<Integer> {
        private final int i;

        public TaskInteger(int i) {
            this.i = i;
        }

        @Override
        public Integer call() throws Exception {
            TimeUnit.SECONDS.sleep(i);
            return i * i;
        }
    }
}
